<template>
    <vxe-modal :title='title'  show-footer :loading="confirmLoading" destroyOnClose width='62%' v-model='visible' @close='handleCancel'>
        <h-form :config='formConfig' ref='formRef' :options='formOptions' v-model='model' @change='formChange' />
        <div slot='footer' style='text-align: center'>
            <a-space>
                <a-button type='danger' @click='handleCancel'> 关闭</a-button>
                <a-button :loading='confirmLoading' type='primary'
                        @click='handleSubmit'> 保存
                </a-button>
            </a-space>
        </div>
        <h-card title='子表'>
            <#if multiSub == true>
                <h-tabs ref='tabsRef' :tab-pane='tabPane' @change='handleTabsChange' :active-key='activeKey'>
                    <template v-for='(item, index) in tabPane' :slot='item.key'>
                        <h-table
                                :key='index + "_"'
                                :height='450'
                                :show-pager='false'
                                :ref='item.key + "Ref"'
                                :columns='columns[item.key]'
                                :auto-load='false'
                                :show-refresh-btn='false'
                                :show-search='false'
                                :show-sort='false'
                                :rowSelection='{ selectedRowKeys, onSelect }'>
                            <template #toolbar>
                                <a-button size='small' type='primary' icon='plus' @click='handleAdd'> 新增</a-button>
                                <a-popconfirm v-if='selectedRowKeys.length' title='确定删除吗?' @confirm='handleBatchDelete(item.key)'>
                                    <a-button size='small' type='danger' ghost icon='delete'>
                                        批量删除
                                    </a-button>
                                </a-popconfirm>
                            </template>
                            <a-space slot='actions' slot-scope='{ row, rowIndex }'>
                                <a @click='handleEdit(row, rowIndex)'>编辑</a>
                                <a-popconfirm  title='确定删除吗?' @confirm='handleDelete(row, item.key)'>
                                    <a class='danger-text'>删除</a>
                                </a-popconfirm>
                            </a-space>
                        </h-table>
                    </template>
                </h-tabs>
            </#if>
            <#if multiSub == false>
                <h-table
                    :height='450'
                    :show-pager='false'
                    ref='tableRef'
                    :columns='columns'
                    :auto-load='false'
                    :show-refresh-btn='false'
                    :show-search='false'
                    :show-sort='false'
                    :rowSelection='{ selectedRowKeys, onSelect }'>
                    <template #toolbar>
                        <a-button size='small' type='primary' icon='plus' @click='handleAdd(null)'> 新增</a-button>
                        <a-popconfirm v-if='selectedRowKeys.length' title='确定删除吗?' @confirm='handleBatchDelete(null)'>
                            <a-button size='small' type='danger' ghost icon='delete'>
                                批量删除
                            </a-button>
                        </a-popconfirm>
                    </template>
                    <a-space slot='actions' slot-scope='{ row, rowIndex }'>
                        <a @click='handleEdit(row, rowIndex)'>编辑</a>
                         <a-popconfirm  title='确定删除吗?' @confirm='handleDelete(row)'>
                                    <a class='danger-text'>删除</a>
                         </a-popconfirm>
                    </a-space>
            </h-table>
            </#if>
            <${webPrefixMiddle}-sub-table-modal ref='subTableFormModal' />
        </h-card>
    </vxe-modal>
</template>

<script>
    import {getAllSubTableData, reloadAllSubTableData, getSetFilesByForm, getSelectOptions, getSetMultipleSelectIdByForm } from '@/utils/formUtil.js';
    import { subTableFormOptions, tabPane, subTableColumns, busiFieldFormSelectConfig } from './data'
    import ${webPrefix}SubTableModal from './${webPrefix}SubTableModal.vue'
    <#assign selectUser = false>
    <#assign selectDept = false>
    <#list fieldData as item>
        <#assign fieldShowType = item.fieldShowType>
        <#if fieldShowType == "13">
            <#assign selectUser = true>
        </#if>
        <#if fieldShowType == "14">
            <#assign selectDept = true>
        </#if>
    </#list>
    <#if selectUser == true || selectDept == true>
    import Vue from 'vue'
    </#if>
    <#if selectUser == true>
    import SysUserSelect from '@/views/components/SysUserSelect.vue';
    Vue.component('SysUserSelect', SysUserSelect);
    </#if>
    <#if selectDept == true>
    import HDepartSelect from '@/views/components/HDepartSelect.vue';
    Vue.component('HDepartSelect', HDepartSelect);
    </#if>

    const baseUrlPrefix = process.env.VUE_APP_API_BASE_URL_PREFIX;

    export default {
        name: '${webPrefix}Modal',
        components: { ${webPrefix}SubTableModal },
        data() {
            return {
                formConfig: {
                    columns: 2
                },
                confirmLoading: false,
                visible: false,
                model: {},
                activeKey: <#if multiSub == true>tabPane[0].key<#elseif multiSub == false>"default"</#if>,
                tabPane: tabPane,
                columns: subTableColumns,
                handleType: '',
                title: '',
                selectedRowKeys: [],
                selectedRows: [],
                formOptions: [
                    { type: "a-input", key: 'id', hidden: true },
                    <#list fieldData as item>
                    <#assign fieldName = item.dbFieldName>
                    <#assign fieldShowName = item.fieldShowName>
                    <#assign isShowList = item.isShowList>
                    <#assign isShowForm = item.isShowForm>
                    <#assign fieldShowType = item.fieldShowType>
                    <#assign fieldMustInput = item.fieldMustInput>
                    <#assign dictOriginType = item.dictOriginType>
                    <#assign dictKey = item.dictKey>
                    <#assign dictCode = item.dictField>
                    <#if isShowForm == true && fieldShowType?has_content>
                    <#switch fieldShowType>
                    <#--            // 文本框-->
                    <#case "1">
                    {
                        title: '${fieldShowName}',
                        key: '${fieldName}',
                        type: "a-input",
                        <#if fieldMustInput == true>
                        rules: [{ required: true, message: '请输入${fieldShowName}' }],
                        </#if>
                        options: {
                            props: {
                                placeholder: '请输入${fieldShowName}',
                            }
                        },
                    },
                    <#break>
                    <#-- 单选框-->
                        <#case "2">
                        <#if dictOriginType == "1">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'h-dict-radio',
                                <#if fieldMustInput == true>
                                rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        dictCode: "${dictCode}",
                                    },
                                },
                            },
                        </#if>
                        <#if dictOriginType == "2">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'h-radio',
                                <#if fieldMustInput == true>
                                rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props:{
                                        options: [],
                                    },
                                },
                            },
                            </#if>
                            <#break>
                    <#--                // 多选框-->
                    <#-- // 多选框-->
                    <#case "3">
                        <#if dictOriginType == "1">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'h-dict-checkbox',
                                <#if fieldMustInput == true>
                                rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        dictCode: "${dictCode}",
                                        options: [],
                                    },
                                },
                            },
                        </#if>
                        <#if dictOriginType == "2">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'h-checkbox',
                                <#if fieldMustInput == true>
                                    rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        options: [],
                                    }
                                },
                            },
                        </#if>
                    <#break>
                    <#--                // 日期(yyyy-MM-dd)-->
                    <#case "5">
                    {
                        title: '${fieldShowName}',
                        key: '${fieldName}',
                        type: 'h-date-picker',
                        <#if fieldMustInput == true>
                        rules: [{ required: true, message: '请选择${fieldShowName}' }],
                        </#if>
                        options: {
                            props: {
                                format:"YYYY-MM-DD",
                                valueFormat:"YYYY-MM-DD",
                                placeholder: "请选择${fieldShowName}",
                            }
                        },
                    },
                    <#break>
                    <#--                // 日期(yyyy)-->
                    <#case "6">
                    {
                        title: '${fieldShowName}',
                        key: '${fieldName}',
                        type: 'h-year-picker',
                        <#if fieldMustInput == true>
                            rules: [{ required: true, message: '请选择${fieldShowName}' }],
                        </#if>
                        options: {
                            props:{
                                placeholder: "请选择${fieldShowName}",
                            }
                        },
                    },
                    <#break>
                    <#--                // 日期(yyyy-MM-dd HH:mm:ss)-->
                    <#case "7">
                    {
                        title: '${fieldShowName}',
                        key: '${fieldName}',
                        type: 'h-date-picker',
                        <#if fieldMustInput == true>
                        rules: [{ required: true, message: '请选择${fieldShowName}' }],
                        </#if>
                        options: {
                            props: {
                                showTime: true,
                                format:"YYYY-MM-DD HH:mm:ss",
                                valueFormat:"YYYY-MM-DD HH:mm:ss",
                                placeholder: "请选择${fieldShowName}",
                            }
                        },
                    },
                    <#break>
                    <#break>
                    <#--                // 多行文本-->
                    <#case "8">
                    {
                        title: '${fieldShowName}',
                        key: '${fieldName}',
                        type: 'a-textarea',
                        span: 2,
                        <#if fieldMustInput == true>
                        rules: [{ required: true, message: '请输入${fieldShowName}' }],
                        </#if>
                        options: {
                            props: {
                                placeholder: '请输入${fieldShowName}',
                            }
                        },
                    },
                    <#break>
                    <#--                // 文件-->
                    <#case "9">
                    {
                        title: '${fieldShowName}',
                        key: '${fieldName}',
                        type: 'h-upload-file',
                        span: 2,
                        <#if fieldMustInput == true>
                        rules: [{ required: true, message: '请上传${fieldShowName}' }],
                        </#if>
                        options: {
                            props: {
                                showSecretLevel: true,
                            },
                            scopedSlots: {
                                secretLevel: ({row, $upload}) => this.$createElement("h-dict-select-user", {
                                    props: {
                                        value: row.secretLevel,
                                    },
                                    on: {
                                        change: (value) => {
                                            row.secretLevel = value;
                                            $upload.triggerChange();
                                        },
                                    },
                                }),
                            },
                        },
                    },
                    <#break>
                    <#--                // 下拉框-->
                        <#case "10">
                        <#if dictOriginType == "1">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'h-dict-select',
                                <#if fieldMustInput == true>
                                    rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        dictCode: "${dictCode}",
                                        options: [],
                                    }
                                },
                            },
                        </#if>
                        <#if dictOriginType == "2">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'h-select',
                                <#if fieldMustInput == true>
                                    rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        options: [],
                                    }
                                },
                            },
                        </#if>
                            <#break>
                        <#--                // 下拉多选-->
                        <#case "11">
                        <#if dictOriginType == "1">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'h-dict-select',
                                <#if fieldMustInput == true>
                                    rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        mode: "multiple",
                                        dictCode: "${dictCode}",
                                        options: [],
                                    }
                                },
                            },
                        </#if>
                        <#if dictOriginType == "2">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'h-select',
                                <#if fieldMustInput == true>
                                    rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        mode: "multiple",
                                        options: [],
                                    }
                                },
                            },
                        </#if>
                            <#break>
                        <#--                // 数值-->
                        <#case "12">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'a-input-number',
                                <#if fieldMustInput == true>
                                    rules: [{ required: true, message: '请输入${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        placeholder: '请输入${fieldShowName}',
                                    },
                                    style:{
                                        width: "100%"
                                    }
                                },
                            },
                            <#break>
                        <#--                // 人员选择-->
                        <#case "13">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'sysUserSelect',
                                <#if fieldMustInput == true>
                                    rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        placeholder: `请选择${fieldShowName}`,
                                    }
                                }   
                            },
                            <#break>
                        <#--                // 部门选择-->
                        <#case "14">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'HDepartSelect',
                                <#if fieldMustInput == true>
                                    rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        placeholder: `请选择${fieldShowName}`,
                                    }
                                },
                            },
                            <#break>
                       <#case "15">
                            {
                                title: '${fieldShowName}',
                                key: '${fieldName}',
                                type: 'h-dict-select-user',
                                <#if fieldMustInput == true>
                                    rules: [{ required: true, message: '请选择${fieldShowName}' }],
                                </#if>
                                options: {
                                    props: {
                                        placeholder: `请选择${fieldShowName}`,
                                    }
                                },
                            },
                            <#break>
                    </#switch>
                    </#if>
                    </#list>
                ],
                url: {
                    queryById: baseUrlPrefix + '/${tableName}Controller/queryVOById',
                    add: baseUrlPrefix + '/${tableName}Controller/add',
                    edit: baseUrlPrefix + '/${tableName}Controller/edit'
                }
            };
        },

        created(){
            getSelectOptions(busiFieldFormSelectConfig, this.formOptions)
        },
        methods: {
            show(record, type = 'edit') {
                this.handleType = type;
                this.visible = true;
                this.title = type === 'edit' ? '编辑' : '新增';
                if (['edit'].includes(type)) {
                    this.$GET(this.url.queryById, { id: record.id }).then((res) => {
                        const { code, data } = res;
                        if (code === 200) {
                            this.model = {
                                ...data,
                                ...getSetFilesByForm(this.formOptions, data, 'set'),
                                ...getSetMultipleSelectIdByForm(this.formOptions, data, 'set')
                            };
                            reloadAllSubTableData({ tableList: this.tabPane, vm: this, data });
                        }
                    });
                } else {
                    this.model = Object.assign({}, record);
                    this.$nextTick(() => {
                        reloadAllSubTableData({ tableList: this.tabPane, vm: this })
                    });
                }
            },
            handleAdd() {
                this.$refs.subTableFormModal.show({}, this.activeKey, "add", formData => {
                    this.handleSubFormCallback(formData, "add")
                })
            },
            handleEdit(row, rowIndex) {
                this.$refs.subTableFormModal.show(row, this.activeKey, "edit", formData => {
                    this.handleSubFormCallback(formData, "edit", rowIndex)
                })
            },
            handleSubFormCallback( values,  operateType, rowIndex ) {
                let tableRef, tableData
                if (this.activeKey) {
                    tableRef = this.$refs[this.activeKey + 'Ref'][0];
                } else {
                    tableRef = this.$refs.tableRef;
                }
                tableData = tableRef.getTableData().fullData;
                if (operateType === 'edit') {
                    tableData[rowIndex] = values;
                } else {
                    tableData.push(values);
                }
                tableRef.reloadData(tableData)
            },
            handleBatchDelete(refKey) {
                if (refKey) {
                    this.$refs[refKey + 'Ref'][0].table.remove(this.selectedRows);
                } else {
                    this.$refs.tableRef.table.remove(this.selectedRows);
                }
                this.selectedRowKeys = []
                this.selectedRows = []
            },
            handleDelete(row, refKey) {
                if (refKey) {
                    this.$refs[refKey + 'Ref'][0].table.remove(row);
                } else {
                    this.$refs.tableRef.table.remove(row);
                }
            },
            getTableData(refKey) {
                if (refKey) {
                    return this.$refs[refKey + 'Ref'][0].getTableData().fullData;
                } else {
                    return this.$refs.tableRef.getTableData().fullData;
                }
            },
            handleSubmit() {
                this.$refs.formRef.getData();
            },
            validateTable() {
                if (this.tabPane.length) {
                    const promises = this.tabPane.map((item) => {
                        return this.$refs[item.key + 'Ref'][0].table.validate(true);
                    });
                    return Promise.all(promises);
                } else {
                    return this.$refs.tableRef.table.validate(true);
                }
            },
            formChange(values) {
                if (this.confirmLoading) return;
                this.validateTable().then(err => {
                    if (!err || err.every(v => v === undefined)) {
                        this.confirmLoading = true;
                        const params = {
                            ...values,
                            ...this.model,
                            ...getSetFilesByForm(this.formOptions, values),
                            ...getSetMultipleSelectIdByForm(this.formOptions, values),
                            ...getAllSubTableData({ tableList: this.tabPane, vm: this,subTableKey: "subList" }),
                        };
                        const url = this.url[this.handleType]
                        this.$POST(url, params).then((res) => {
                            const { code = 0 } = res;
                            if (code === 200) {
                                this.$message.success(this.title + '成功');
                                this.handleCancel();
                                this.$emit('change');
                            }
                        }).finally(() => {
                            this.confirmLoading = false;
                        });
                    }
                });
            },
            onSelect(selectedRowKeys, selectedRows) {
                this.selectedRowKeys = selectedRowKeys;
                this.selectedRows = selectedRows;
            },
            handleTabsChange(key) {
                this.activeKey = key;
                this.selectedRowKeys = []
                this.selectedRows = []
            },
            handleCancel() {
                this.confirmLoading = false;
                this.selectedRowKeys = [];
                this.selectedRows = [];
                this.visible = false;
            },
        },
    };
</script>

<style scoped lang='less'>

</style>